package org.yystory.ui;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.yystory.entity.Sequence;
import org.yystory.service.StoryService;
import org.yystory.utility.ErrorParser;

public class GetSequenceServlet extends HttpServlet {

	private static final long serialVersionUID = -4162194911890315588L;

	public GetSequenceServlet() {
		super();
	}

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		response(request, response);
	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		response(request, response);
	}

	private void response(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		try {
			int id = Integer.parseInt(request.getParameter("id"));
			response.setContentType("audio/mpeg3");
			Sequence sequence = StoryService.findSequence(id);
			byte[] data = sequence.getData();
			response.getOutputStream().write(data);
			response.setStatus(HttpServletResponse.SC_OK);
			response.flushBuffer();
			response.getOutputStream().close();
		} catch (Exception e) {
			response.getWriter().print(
					ErrorParser.parseError("GetSequenceServlet", e.getClass()
							.getName() + ":" + e.getMessage()));
			response.getWriter().close();
		}
	}

}
